package homework.tcp;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;

public class ClientSend implements Runnable {

    //存储当前客户端
    private Socket socket;

    //线程持续执行条件标识符
    private boolean b = true;

    public ClientSend(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {

        BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
        OutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            outputStream = this.socket.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            System.out.println("请输入你的姓名(创建用户名，不包含空格)");
            String line = sc.readLine();
            writer.write(line);
            writer.flush();
            System.out.println("创建完成！已进入聊天室--------------");

            //选择和谁连接
//            System.out.println("创建完毕!请选择和哪个人连接通信");
//            String she = sc.readLine();
//            writer.write(she);
//            writer.flush();

            while (b) {
                outputStream = this.socket.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                line = sc.readLine();

                writer.write(line + "\n");
                writer.flush();
            }
        } catch (SocketException e) {
            System.out.println("Socket已关闭");
        } catch (Exception e) {
            System.out.println("大异常");
        } finally {
            b = false;
            try {
                if (writer != null) writer.close();
                if (outputStream != null) outputStream.close();
                sc.close();
                socket.close();
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}
